#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#       gui.py
#
#       Copyright (C) 2010  Catullus Cassius
#
#       This file is part of python-vkontakte-player.
#
#       This program is free software: you can redistribute it and/or modify
#       it under the terms of the GNU General Public License as published by
#       the Free Software Foundation, either version 3 of the License, or
#       (at your option) any later version.
#
#       This program is distributed in the hope that it will be useful,
#       but WITHOUT ANY WARRANTY; without even the implied warranty of
#       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#       GNU General Public License for more details.
#
#       You should have received a copy of the GNU General Public License
#       along with this program.  If not, see <http://www.gnu.org/licenses/>.


import PyQt4
import sys

from mainwindow import Ui_MainWindow
import api, api_exception
import player
import login
import config
import shelve

api_id = 2004200

class mainWindow(PyQt4.QtGui.QMainWindow, Ui_MainWindow):
	def __init__(self):
		super(mainWindow, self).__init__()
		self.setupUi(self)

		self.player = player.player()

		self.connect(self.searchPushButton, PyQt4.QtCore.SIGNAL("clicked()"), self.search)
		self.connect(self.addPushButton,  PyQt4.QtCore.SIGNAL("clicked()"), self.addToPlayList)
		self.connect(self.playPushButton, PyQt4.QtCore.SIGNAL("clicked()"), self.player.play)
		self.connect(self.pausePushButton, PyQt4.QtCore.SIGNAL("clicked()"), self.pause)
		self.connect(self.stopPushButton, PyQt4.QtCore.SIGNAL("clicked()"), self.stop)
		self.connect(self.nextPushButton, PyQt4.QtCore.SIGNAL("clicked()"), self.next)
		self.connect(self.prevPushButton, PyQt4.QtCore.SIGNAL("clicked()"), self.prev)
		self.connect(self.modeButtonGroup, PyQt4.QtCore.SIGNAL("buttonClicked(QAbstractButton*)"), self.set_mode)
		self.connect(self.singleCheckBox, PyQt4.QtCore.SIGNAL("stateChanged(int)"), self.set_single)
		self.connect(self.consumeCheckBox, PyQt4.QtCore.SIGNAL("stateChanged(int)"), self.set_consume)
		self.connect(self.saveToPushButton, PyQt4.QtCore.SIGNAL("clicked()"), self.save_playlist)
		self.connect(self.loadFromPushButton, PyQt4.QtCore.SIGNAL("clicked()"), self.load_playlist)
		self.connect(self.playlistTableView, PyQt4.QtCore.SIGNAL("doubleClicked(const QModelIndex&)"), self.playlist_dbclick)
		self.connect(self.loginPushButton, PyQt4.QtCore.SIGNAL("clicked()"), self.openLoginDialog)
		self.connect(self.licensePushButton, PyQt4.QtCore.SIGNAL("clicked()"), self.show_license)

		self.playlistTableView.keyPressEvent = self.playlistTableViewKey
		self.playlistTableView.setModel(self.player.playlist_model)

		self.seekSlider.setMediaObject(self.player.mediaObject)
		self.volumeSlider.setAudioOutput(self.player.audioOutput)

		self.searchTableWidget.setColumnCount(4)

		#loading session
		session = config.load_session()
		if session != None:
			self.vk = api.Api(api_id, session)

		self.playlist = []
		self.highlighted = -1

	def search(self):
		query=unicode(self.searchLineEdit.text())
		try:
			self.resp = self.vk.method('audio.search', q=query)
		except api_exception.MethodErr, e:
			msg = PyQt4.QtGui.QMessageBox(self)
			msg.setText(e.error_msg+'\n'+str(e.request_params))
			msg.setWindowTitle('Api Error')
			msg.exec_()
			return

		self.searchTableWidget.setRowCount(len(self.resp)-1)
		i=0
		for song_info in self.resp[1:]:
			artist = PyQt4.QtGui.QTableWidgetItem(song_info['artist'])
			title = PyQt4.QtGui.QTableWidgetItem(song_info['title'])
			duration = PyQt4.QtGui.QTableWidgetItem(song_info['duration'])
			bitrate = PyQt4.QtGui.QTableWidgetItem('')
			self.searchTableWidget.setItem(i, 0, artist)
			self.searchTableWidget.setItem(i, 1, title)
			self.searchTableWidget.setItem(i, 2, duration)
			self.searchTableWidget.setItem(i, 3, bitrate)
			i=i+1

	def addToPlayList(self):
		indexes = self.search_selected()
		if len(indexes) == 0:
			return
		for i in indexes:
			self.playlist.append(self.resp[i+1])
			self.player.add(self.resp[i+1])

	def search_selected(self):
		indexes = []
		for selectionRange in self.searchTableWidget.selectedRanges():
			indexes.extend(range(selectionRange.topRow(), selectionRange.bottomRow()+1))
		return indexes

	def playlist_selected(self):
		indexes = []
		for index in self.playlistTableView.selectedIndexes():
			if not index.row() in indexes:
				indexes.append(index.row())
		return indexes

	def highlight(self, pos):
		if self.highlighted != -1:
			for i in range(4):
				self.playlistTableView.item(self.highlighted, i).setBackground(PyQt4.QtGui.QBrush(PyQt4.QtGui.QColor("white")))
		if pos != -1:
			for i in range(4):
				self.playlistTableView.item(pos, i).setBackground(PyQt4.QtGui.QBrush(PyQt4.QtGui.QColor("yellow")))
		self.highlighted = pos

	def playlistTableViewKey(self, event):
		if event.key() == PyQt4.QtCore.Qt.Key_Delete:
			self.delete(self.playlist_selected())
		elif event.key() == PyQt4.QtCore.Qt.Key_Enter or event.key() == PyQt4.QtCore.Qt.Key_Return:
			self.play(self.playlist_selected()[0])
		PyQt4.QtGui.QTableWidget.keyPressEvent(self.playlistTableView, event)

	def playlist_dbclick(self, index):
		print "Double click!"
		self.play(index.row())

	def delete(self, indexes):
		indexes.sort()
		indexes.reverse()
		self.player.delete(indexes)
		for i in indexes:
			self.playlist.pop(i)

	def save_playlist(self):
		fileDialog = PyQt4.QtGui.QFileDialog()
		fileDialog.setFileMode(PyQt4.QtGui.QFileDialog.AnyFile)
		fileDialog.setAcceptMode(PyQt4.QtGui.QFileDialog.AcceptSave)
		fname = fileDialog.getSaveFileName()
		#should use some file checks
		s = shelve.open(unicode(fname), 'c')
		s['playlist'] = self.playlist
		s.close()

	def load_playlist(self):
		fileDialog = PyQt4.QtGui.QFileDialog()
		fileDialog.setFileMode(PyQt4.QtGui.QFileDialog.AnyFile)
		fileDialog.setAcceptMode(PyQt4.QtGui.QFileDialog.AcceptOpen)
		fname = fileDialog.getOpenFileName()
		#should use some file checks
		s = shelve.open(unicode(fname), 'r')
		self.playlist.extend(s['playlist'])

		for song_info in s['playlist']:
			self.player.add(song_info)
		s.close()


	def play(self, pos):
		self.player.stop()
		self.player.position = pos
		self.player.play()
	def pause(self):
		self.player.pause()
	def stop(self):
		self.player.stop()
	def prev(self):
		self.player.prev()
	def next(self):
		self.player.next()

	def set_mode(self, button):
		mode = str(button.text())
		self.player.mode = mode.lower()
		self.player.update_cached()

	def set_single(self, single):
		self.player.single = bool(single)
		self.player.update_cached()

	def set_consume(self, consume):
		self.player.consume = bool(consume)
		self.player.update_cached()

	def openLoginDialog(self):
		self.lD = login.loginDialog(self)
		self.lD.returnSession = self.returnSession
		self.lD.show()

	def returnSession(self, session):
		self.lD.close()
		config.save_session(session)
		self.vk = api.Api(api_id, session)

	def show_license(self):
		license = '<font color=green>Copyright &copy; 2010 Catullus Cassius.</font><p>\
		This program is free software: you can redistribute \
		it and/or modify it under the terms of the GNU General Public License \
		as published by the Free Software Foundation, either version 3 \
		of the License, or (at your option) any later version. \
		This program is distributed in the hope that it will be \
		useful, but WITHOUT ANY WARRANTY; without even the implied warranty \
		of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. \
		See the GNU General Public License for more details. You should have \
		received a copy of the GNU General Public License along with \
		This program.  If not, see <a href="http://gnu.org/licenses/">\
		http://www.gnu.org/licenses</a>.'
		licenseDialog = PyQt4.QtGui.QDialog(self)
		layout = PyQt4.QtGui.QGridLayout(licenseDialog)
		licenseDialog.setLayout(layout)
		licenseDialog.setMinimumSize(min(self.width(),
                int(PyQt4.QtGui.QApplication.desktop().availableGeometry()
                    .width() / 2)),
                int(PyQt4.QtGui.QApplication.desktop().availableGeometry()
                    .height() / 2))
		licenseTextBrowser = PyQt4.QtGui.QTextBrowser(licenseDialog)
		licenseTextBrowser.setOpenExternalLinks(True)
		licenseTextBrowser.setHtml(PyQt4.QtCore.QString(license))
		layout.addWidget(licenseTextBrowser, 0, 0, 1, 1)
		licenseDialog.setWindowTitle("License")
		licenseDialog.exec_()


